package com.coding.v2;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @description <功能描述>
 * @author: <user>
 * @Date: 2023/7/26 13:43
 */
public class EntityGenerator {

    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/test_db?useSSL=false&serverTimezone=UTC";
        String username = "root";
        String password = "root123";
        String tableName = "t_user"; // 指定你想要生成Entity的表名

        try (Connection connection = DriverManager.getConnection(url, username, password)) {
            DatabaseMetaData metaData = connection.getMetaData();
            ResultSet columns = metaData.getColumns(null, null, tableName, null);

            List<ColumnInfo> columnMappings = new ArrayList<>();
            while (columns.next()) {
                String columnName = columns.getString("COLUMN_NAME");
                String columnType = columns.getString("TYPE_NAME");
                String javaType = sqlTypeToJavaType(columnType);
                String fieldName = toCamelCase(columnName);
                columnMappings.add(new ColumnInfo(columnName, fieldName, javaType));
            }

            generateEntityClass(tableName, columnMappings);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将sqlType转为JavaType
     * @param sqlType
     * @return
     */
    private static String sqlTypeToJavaType(String sqlType) {
        // 这里简单示例，你可以根据实际数据库类型进行映射
        switch (sqlType) {
            case "VARCHAR":
            case "CHAR":
                return "String";
            case "INT":
                return "int";
            case "BIGINT":
                return "long";
            case "DECIMAL":
                return "BigDecimal";
            case "DATE":
            case "DATETIME":
                return "String";
            // Add more mappings as needed for your database
            default:
                return "Object";
        }
    }

    /**
     * 将下划线单词转为驼峰
     * @param input
     * @return
     */
    private static String toCamelCase(String input) {
        StringBuilder result = new StringBuilder();
        String[] words = input.toLowerCase().split("_");
        for (int i = 0; i < words.length; i++) {
            String word = words[i];
            result.append(i == 0 ? word : capitalize(word));
        }
        return result.toString();
    }

    private static String capitalize(String input) {
        return input.substring(0, 1).toUpperCase() + input.substring(1);
    }

    /**
     * 生成EntityClass文件
     * @param table
     * @param columnMappings
     */
    private static void generateEntityClass(String table, List<ColumnInfo> columnMappings) {
        try {
            Configuration cfg = new Configuration(Configuration.VERSION_2_3_31);
            cfg.setClassForTemplateLoading(EntityGenerator.class, "/");
            cfg.setDefaultEncoding("UTF-8");
            cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

            Template template = cfg.getTemplate("template/entity_template.ftl");
            //Template template = cfg.getTemplate("template/entity_xml_template.ftl");


            Map<String, Object> dataModel = new HashMap<>();
            dataModel.put("tableName", table);
            dataModel.put("className", toCamelCase(table));
            dataModel.put("columns", columnMappings);


//            Writer out = new FileWriter(new File("src/main/java/" + toCamelCase(table) + ".java"));
            template.process(dataModel,  new OutputStreamWriter(System.out));

            System.out.println("Java文件生成成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


